#!/bin/sh
#this is called from 'init', runs as parallel process.
#110710 rewritten for kernel with hid and usb drivers builtin, and without my usb-storage patch.
#110713 have put my usb-storage patch back in to kernel (2.6.39-3).
#120330 mmc drives may be slow to become ready, so add them in here.

mount -t usbfs none /proc/bus/usb

#sleep 1
USBSTORAGES=0 ; CNTUSB=0
while [ $USBSTORAGES -eq 0 ];do
 sleep 1
 echo -n "." > /dev/console
 CNTUSB=$(($CNTUSB+1))
 [ $CNTUSB -gt 5 ] && break
 #v412 bug, ubuntu kernel, got duplicate 'device found at 2', need 'sort -u'...
 USBSTORAGES=`/bin/dmesg | grep "usb-storage: device found at" | sort -u | wc -l`
 [ $USBSTORAGES -eq 0 ] && break
 AVAILABLEUSBSTORAGES=`/bin/dmesg | grep "usb-storage: device scan complete" | wc -l`
 [ $USBSTORAGES -ne $AVAILABLEUSBSTORAGES ] && USBSTORAGES=0
done

#i want this to work with kernel that does not have my usb-storage patch, feedback is that 3 secs is enough...
while [ $CNTUSB -lt 3 ];do
 sleep 1
 CNTUSB=$(($CNTUSB+1))
 echo -en "\\033[1;33m.\\033[0;39m" >/dev/console #yellow dot
done

#wait for usb partitions to become available...
#entries in /sys/block show up, but ex /sys/block/sda/sda1 takes a bit longer...
#note, if usb card-reader plugged in but no cards inserted, this will timeout...
#note, will also timeout if usb optical drive (sr), but ok, they need extra time...
ALLUSBDRVS="`find /sys/block -maxdepth 1 -name 'sd*' -o -name 'sr*' | xargs -l readlink 2>/dev/null | grep '/usb[0-9]' | rev | cut -f 1 -d '/' | rev | tr '\n' ' '`"
[ "$ALLUSBDRVS" = " " ] && ALLUSBDRVS=""
for ONEDRV in $ALLUSBDRVS
do
 while [ ! -e /sys/block/${ONEDRV}/${ONEDRV}1 ];do
  sleep 1
  echo -en "\\033[1;31m.\\033[0;39m" >/dev/console #red dot
  CNTUSB=$(($CNTUSB+1))
  [ $CNTUSB -gt 6 ] && break
 done
 #force update of /proc/partitions...
 dd if=/dev/${ONEDRV} of=/dev/null bs=512 count=1 >/dev/null 2>&1
done

#120330 probe for mmc drives...
MMCDRVS=""
if [ "`grep '^mmc' /tmp/ALLDRVS0`" = "" ];then  #find out if already available.
 [ "`lsmod | grep '^mmc'`" != "" ] && MMCDRVS="`find /sys/block -maxdepth 1 -name 'mmc*' | tr '\n' ' '`"
 [ "$MMCDRVS" = " " ] && MMCDRVS=""
fi

echo -n "$ALLUSBDRVS" > /tmp/flag-usb-ready
[ "$MMCDRVS" ] && echo -n " ${MMCDRVS}" >> /tmp/flag-usb-ready

###end###
